# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote)) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
  select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
  deframe()

diffData <- read_csv("Markers.csv")

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
  .$Metabolite

classNotes <- unique(sampleInfo$ClassNote)

parent <- "./"
fileName <- paste0(parent, "/../uni/AllMet_Test.csv")
outFileName <- paste0(parent, "/Markers_log2FC_FDR_Bar_Plot.pdf")
pValueData <- read_csv(fileName) %>%
  filter(Metabolite %in% diffNames) %>%
  arrange(P)
names <- pValueData$Metabolite

data <- read.csv(opt$i, header = T, stringsAsFactors = FALSE) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  inner_join(sampleInfo, by = c("SampleID"))

head(data)

pValueData
pic_df <- pValueData %>%
  arrange(desc(log2FC)) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    fdr <- result %>%
      .$FDR
    fill <- if (fdr < 0.001) "High" else if (fdr < 0.01) "Median" else if (fdr < 0.05) "Low"  else "None"
    result$fill <- fill
    result
  }) %>%
  ungroup() %>%
  mutate(fill = factor(fill, levels = rev(c("None", "Low", "Median", "High"))))
fillCols <- tibble(sig = c("Low", "Median", "High", "None"), col = c("#00BFC4", "#F8766D", "red", "gray")) %>%
  deframe()
labels <- tibble(sig = c("Low", "Median", "High", "None"), col = c("FDR<0.05", "FDR<0.01", "FDR<0.0001", "FDR>=0.05")) %>%
  deframe()


pic_df %>%
  as.data.frame() %>%
  head() %>%
  print()
pic_df$lab_y <- -0.05 * pic_df$log2FC / abs(pic_df$log2FC)
pic_df$hjust <- 1
pic_df$hjust[pic_df$log2FC < 0] <- 0
pic_df$num <- 1:nrow(pic_df)


pic <- ggplot(pic_df) +
  geom_abline(linetype = "solid", intercept = 0, slope = 0, size = 1, colour = 'black') +
  geom_abline(linetype = "dashed", intercept = 0.25, slope = 0, size = 1, colour = 'gray') +
  geom_abline(linetype = "dashed", intercept = -0.25, slope = 0, size = 1, colour = 'gray') +
  geom_bar(aes(x = Metabolite, y = log2FC, fill = fill), position = "identity", stat = "identity") +
  geom_text(aes(label = Metabolite, x = num, y = lab_y, hjust = hjust),
            vjust = 0.5, color = "Black", size = 5, angle = 90) +
  theme_classic() +
  xlab(NULL) +
  theme(
    text = element_text(size = 18, color = "black"),
    axis.text = element_text(size = 18),
    axis.title.y = element_text(size = 20),
    legend.title = element_text(size = 24),
    plot.margin = unit(c(.5, .5, .5, .5), "cm"),
    panel.grid = element_blank(),
    axis.line.y = element_line(size = .8, colour = "black", linetype = 1),
    axis.line.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks = element_blank(),
    axis.ticks.y = element_blank()) +
  expand_limits(y = c(-1,1)) +
  scale_fill_manual("FDR_level", values = fillCols, labels = labels)

metaboliteNum <- pic_df %>%
  .$Metabolite %>%
  unique() %>%
  length()
pic_df
width <- 3 + metaboliteNum * 0.25
width
ggsave(filename = outFileName, plot = pic, width = width, height = 8, limitsize = F, family = "sans")


